<?php

/**
 * User: Monjra
 * Date: 2020/12/09 17:10
 */

namespace app\admin\controller;

use think\Db;
use think\Request;
use app\index\model\User;
use app\admin\model\Service;
use app\api\service\OssService;
use app\wechat\model\MessageTemplate;
use Wechat\Services\WechatService;

class Staff extends Base
{
    public function index()
    {
        return $this->fetch();
    }

    public function _users()
    {
        $query = Service::where('role', Service::ROLE_SERVICE)->with('children');
        cookie('service_id') && $query->where('id', cookie('service_id'));
        /**
         * @var Collection
         */
        $services = $query->select();
        // $users = User::where('service_id', '>', 0)->where('department_id', '>', 0)->where('market_id', '>', 0)->where('shop_id', '>', 0)->limit(200)->select();


        $data = $services->map(function (Service $service) {
            $sex = config('sex');
            return [
                'id' => $service->id,
                'title' => '【客服】' . $service->user_name,
                'type' => 'service',
                'children' => $service->children()->select()->map(fn ($department) => [
                    'id' => $department->id,
                    'title' => '【事业中心】' . $department->service_name,
                    'user_name' => $department->user_name,
                    'type' => 'department',
                    'children' => $department->children()->select()->map(fn ($shop) => [
                        'id' => $shop->id,
                        'title' => '【门店】' . $shop->service_name,
                        'user_name' => $shop->user_name,
                        'type' => 'shop',
                        'children' => Service::field([
                            'IFNULL(ws_users.id,0)' => 'user_id',
                            'ws_users.name',
                            'ws_users.shop_id',
                            'ws_users.department_id',
                            'ws_users.service_id',
                            'ws_users.mobile',
                            'ws_users.sex',
                            'ws_users.age',
                            'ws_users.status',
                            'ws_users.enable',
                            'ws_services.user_name' => 'market',
                            'ws_services.id' => 'market_id',
                            'ws_services.superior_id',
                        ])->join('ws_users', 'ws_users.market_id = ws_services.id', 'left')->where('superior_id', $shop->id)->where('role', Service::ROLE_MARKET)->select()->map(fn ($user) => [
                            'id' => $user->user_id,
                            'title' => $user->user_id ? '【顾客】' . $user->name : '未绑定顾客',
                            'type' => 'user',
                            'isJump' => true,
                            'link' => url('examine/edit', ['id' => $user->user_id]),
                            'market' => $user->market,
                            'market_id' => $user->market_id,
                            'shop_id' => $user->shop_id ?: $user->superior_id,
                            'department_id' => $user->department_id,
                            'service_id' => $user->service_id,
                            'mobile' => $user->mobile,
                            'sex' => $sex[$user->sex] ?? '未公开',
                            'age' => $user->age,
                            'status' => User::STATUS_MAP[$user->status] ?? '',
                            'enable' => $user->enable ? '启用' : '禁用',
                        ])
                    ])->values()
                ])->values()
            ];
        })->values();
        return json([
            'code' => 0,
            'msg' => '',
            'data' => $data
        ]);
    }

    public function users()
    {
        $query = Service::where('role', Service::ROLE_SERVICE)->with('children');
        cookie('service_id') && $query->where('id', cookie('service_id'));
        /**
         * @var Collection
         */
        $services = $query->select();
        // $users = User::where('service_id', '>', 0)->where('department_id', '>', 0)->where('market_id', '>', 0)->where('shop_id', '>', 0)->limit(200)->select();


        $data = $services->map(function (Service $service) {
            $sex = config('sex');
            return [
                'id' => $service->id,
                'title' => '【客服】' . $service->user_name,
                'type' => 'service',
                'children' => $service->children()->select()->map(fn ($department) => [
                    'id' => $department->id,
                    'title' => '【事业中心】' . $department->service_name,
                    'user_name' => $department->user_name,
                    'type' => 'department',
                    'children' => Service::where('role', Service::ROLE_SHOP)->where('superior_id', 'in', $department->children()->column('id'))->select()->map(fn (Service $shop) => [
                        'id' => $shop->id,
                        'title' => '【门店】' . $shop->service_name,
                        'user_name' => $shop->user_name,
                        'market_id' => $shop->superior_id,
                        'type' => 'shop',
                        'children' => User::where('shop_id', $shop->id)->select()->map(fn ($user) => [
                            'id' => $user->id,
                            'title' => $user->id ? '【顾客】' . $user->name : '未绑定顾客',
                            'type' => 'user',
                            'isJump' => true,
                            'link' => url('examine/edit', ['id' => $user->id]),
                            'market' => $shop->superior->service_name ?? '',
                            'market_id' => $shop->superior_id,
                            'shop_id' => $shop->id,
                            'department_id' => $user->department_id,
                            'service_id' => $user->service_id,
                            'mobile' => $user->mobile,
                            'sex' => $sex[$user->sex] ?? '未公开',
                            'age' => $user->age,
                            'status' => User::STATUS_MAP[$user->status] ?? '',
                            'enable' => $user->enable ? '启用' : '禁用',
                        ])
                    ])->values()
                ])->values()
            ];
        })->values();
        return json([
            'code' => 0,
            'msg' => '',
            'data' => $data
        ]);
    }
    /**
     * 更新用户
     *
     * @param \think\Request $request
     * @return void
     */
    public function enableUsers(Request $request)
    {
        if ($this->request->isAjax()) {
            $post = $request->post();
            $enable = $post['is_enable'] == 'enable' ? 1 : 0;
            $data = $post['data'];
            $condition = [];
            $update = ['enable' => $enable];
            switch ($data['type']) {
                case 'user':
                    $condition['id'] = $data['id'];
                    break;
                case 'shop':
                    $condition['shop_id'] = $data['id'];
                    break;
                case 'department':
                    $condition['department_id'] = $data['id'];
                    break;
                case 'market':
                    $condition['market_id'] = $data['id'];
                    break;
                case 'service':
                    $condition['service_id'] = $data['id'];
                    break;
                default:
                    return [
                        'code' => -1,
                        'msg' => '无效的分级',
                        'data' => ''
                    ];
            }
            $res = User::update($update, $condition);
            return [
                'code' => 0,
                'data' => $res,
                'msg' => '已' . ($enable ? '启用' : '禁用')
            ];
        }
    }

    public function read($id)
    {
        $user = User::find($id);
        $this->assign('user', $user);
        return $this->fetch();
    }

    public function read_file($id)
    {
        $user = User::find($id);

        if ($user->user_file1) {
            $user->user_file1_pre = OssService::previewUrl($user->user_file1, '项目消耗表');
        }
        if ($user->user_file2) {
            $user->user_file2_pre = OssService::previewUrl($user->user_file2, '见诊档案');
        }
        if ($user->user_file3) {
            $user->user_file3_pre = OssService::previewUrl($user->user_file3, '咨询记录表');
        }
        $this->assign('info', $user);
        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            try {
                $post = $this->request->post();
                $post['status'] = !empty($post['status']) ? User::STATUS_PASS : User::STATUS_NO_PASS;
                $user = new User($post);
                $user->allowField(true)->save();
                return [
                    'code' => 1,
                    'msg' => '添加成功',
                    'data' => url('admin/staff/index')
                ];
            } catch (\Throwable $th) {
                return [
                    'code' => -1,
                    'msg' => '添加失败: ' . $th->getMessage(),
                ];
            }
        }
        $id = intval($this->request->get('id', 0));
        $type = $this->request->get('type');
        if (!$id && 'user' == $type) {
            $id = intval($this->request->get('market_id', 0));
            $type = 'market';
        }
        $assign = [
            'service_id' => 0,
            'market_id' => 0,
            'department_id' => 0,
            'shop_id' => 0,
        ];
        $kfs = Service::field(['id', 'role', 'user_name', 'service_name', 'superior_id'])->select();
        switch ($type) {
            case 'service':
                $assign['service_id'] = $id;
                break;
            case 'department':
                $assign['department_id'] = $id;
                $assign['service_id'] = $kfs->where('id', $id)->first()->superior_id ?? 0;
                break;
            case 'market':
                $assign['market_id'] = $id;
                $assign['department_id'] = $kfs->where('id', $id)->first()->superior_id ?? 0;
                $assign['service_id'] = $kfs->where('id', $assign['department_id'])->first()->superior_id ?? 0;
                break;
            case 'shop':
                $assign['shop_id'] = $id;
                $assign['market_id'] = $kfs->where('id', $id)->first()->superior_id ?? 0;
                $assign['department_id'] = $kfs->where('id', $assign['market_id'])->first()->superior_id ?? 0;
                $assign['service_id'] = $kfs->where('id', $assign['department_id'])->first()->superior_id ?? 0;
                break;
            case 'user':
                $user = User::find($id);
                $assign['shop_id'] = $user->shop_id;
                $assign['market_id'] = $user->market_id;
                $assign['department_id'] = $user->department_id;
                $assign['service_id'] = $user->service_id;
                break;
            default:
                break;
        }
        $assign['kfs'] = $kfs->groupBy('role');
        $this->assign($assign);
        return $this->fetch();
    }

    public function pushMessage()
    {
        if ($this->request->isPost()) {
            $ids = $this->request->post('ids/a');
            $title = $this->request->post('title');
            $message_type = $this->request->post('message_type');
            $effect = $this->request->post('effect');
            $notice = $this->request->post('notice');
            if (!$title || !$message_type || !$effect || !$notice) {
                return ['code' => -1, 'msg' => '请补全推送的消息'];
            }

            $users = User::where('id', 'in', $ids)->whereNotNull('openid')->where('openid', '<>', '')->select();
            if ($users->isEmpty()) {
                return ['code' => -1, 'msg' => '无效用户，无法推送'];
            }

            $template = MessageTemplate::where('title', '检查结果通知')->whereNull('deleted_at')->find();
            if (!$template) {
                return ['code' => -1, 'msg' => '没找到消息模板，无法推送'];
            }
            $success = $fail = 0;
            try {
                foreach ($users as $user) {
                    try {
                        WechatService::sendTemplateMessage($user->openid, $template->template_id, null, [
                            'first' => $title,
                            'keyword1' => $effect,
                            'keyword2' => $message_type,
                            'keyword3' => date('Y-m-d H:i:s'),
                            'remark' => $notice
                        ]);
                        $success++;
                    } catch (\Throwable $th) {
                        $fail++;
                    }
                }
            } catch (\Throwable $th) {
                return ['code' => -1, 'msg' => '推送失败', 'data' => $th->getMessage()];
            }
            return ['code' => 0, 'msg' => '推送成功', 'data' => ['success' => $success, 'fail' => $fail]];
        }
        $ids = $this->request->get('ids');
        $users = User::where('id', 'in', $ids)->select();
        $this->assign([
            'list' => $users,
            'ids' => $ids,
            'message' => config('push_message')
        ]);
        return $this->fetch();
    }

    public function getMessage($key)
    {
        return config('push_message')[$key] ?? [];
    }

    public function deleteUser($id)
    {
        if ($this->request->isAjax()) {
            $user = User::find($id);
            $user && $user->delete();
            return [
                'code' => 0,
                'msg' => '删除成功'
            ];
        }
    }
}
